const app = getApp()
const util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    examInfo:{},
    studyInfo:{},
    trainInfo: {},
    tabList:[{name: '理财经理', active:true, type: 'student'}, {name: '客户经理', active:false, type: 'admin'}],
    type: 'student',
    url: 'https://cpl-test.zhilingsd.com/h5/static/img/hot-bg.png',
    hasTips: true,
    fields: [],
    userFields: [{
      prop: 'name',
      label: '姓名',
      width: 240
    },
    {
      prop: 'siteName',
      label: '网点名称',
      width: 260
    },
    {
      prop: 'date',
      label: '最后活跃时间',
      width: 250
    }],
    numFields: [{
      prop: 'name',
      label: '姓名',
      width: 160
    },
    {
      prop: 'siteName',
      label: '网点名称',
      width: 260
    },
    {
      prop: 'num',
      label: '活跃次数',
      width: 130
    },
    {
      prop: 'useTime',
      label: '累计时长',
      width: 150
    },
    {
      prop: 'date',
      label: '最后活跃时间',
      width: 170
    }],
    timeFields: [{
      prop: 'name',
      label: '姓名',
      width: 160
    },
    {
      prop: 'siteName',
      label: '网点名称',
      width: 260
    },
    {
      prop: 'useTime',
      label: '累计时长',
      width: 155
    },
    {
      prop: 'date',
      label: '最后活跃时间',
      width: 175
    }],
    fields1: [{
      prop: 'name',
      label: '姓名',
      width: '160'
    },
    {
      prop: 'num',
      label: '访问次数',
      width: '130'
    },
    {
      prop: 'studyNum',
      label: '学习次数',
      width: '130'
    },
    {
      prop: 'rehearsalNum',
      label: '演练次数',
      width: '130'
    },
    {
      prop: 'passNum',
      label: '通关次数',
      width: '130'
    },
    {
      prop: 'avgRehearsalScore',
      label: '演练均分',
      width: '130'
    },
    {
      prop: 'avgPassScore',
      label: '通关均分',
      width: '130'
    },
    {
      prop: 'totalTime',
      label: '累计时长',
      width: '150'
    }],
    fields2: [{
      prop: 'name',
      label: '姓名',
      width: '160'
    },
    {
      prop: 'num',
      label: '访问次数',
      width: '130'
    },
    {
      prop: 'studyNum',
      label: '学习次数',
      width: '130'
    },
    {
      prop: 'rehearsalNum',
      label: '演练次数',
      width: '130'
    },
    {
      prop: 'passNum',
      label: '通关次数',
      width: '130'
    },
    {
      prop: 'avgRehearsalScore',
      label: '演练均分',
      width: '130'
    },
    {
      prop: 'avgPassScore',
      label: '通关均分',
      width: '130'
    },
    {
      prop: 'totalTime',
      label: '累计时长',
      width: '150'
    }],
    fields3: [{
      prop: 'name',
      label: '姓名',
      width: '250'
    },
    {
      prop: 'num',
      label: '演示次数',
      width: '250'
    },
    {
      prop: 'totalTime',
      label: '累计时长',
      width: '250'
    }],
    fields4: [{
      prop: 'name',
      label: '姓名',
      width: '375'
    },
    {
      prop: 'num',
      label: '生成份数',
      width: '375'
    }],
    fields5: [{
      prop: 'name',
      label: '姓名',
      width: '220'
    },
    {
      prop: 'num',
      label: '发起次数',
      width: '150'
    },
    {
      prop: 'receiveNum',
      label: '会客次数',
      width: '150'
    },
    {
      prop: 'avgTime',
      label: '平均时长',
      width: '230'
    }],
    fields6: [{
      prop: 'nameAndTime',
      double: true,
      label: '考试主题',
      width: '350'
    },
    {
      prop: 'enterNum',
      label: '实际参与',
      width: '130'
    },
    {
      prop: 'coachingNum',
      label: '计划参与',
      width: '130'
    },
    {
      prop: 'handler',
      label: '操作',
      width: '140'
    }],
    list: [],
    total: 0,
    startdate: (util.timestampToTime(Date.now() - 7 * 60 * 60 * 24 * 1000)),
    enddate: (util.timestampToTime(Date.now())),
    // startdate: (util.timestampToTime(new Date().setDate(1))),
    // enddate: (util.timestampToTime(new Date().setDate(1))),
    navBarHeight: app.globalData.navBarHeight,
    orgId: app.globalData.userInfo.orgId,
    bankList: [],
    bankidList: [],
    bankindex: '',
    branchList: [],
    branchidList: [],
    branchidindex: '',
    subBranchList: [],
    subBranchidList: [],
    subBranchindex: '',
    siteList: [],
    siteidList: [],
    siteindex: '',
    selectlist: [{name: '银行', num: 500, active: false}, {name: '分行', num: 500, active: false}, {name: '支行', num: 10000, active: false}, {name: '网点', num: 10000, active: false}],
    tablist: [],
    setTitleName: '活跃数',
    sortField: '',
    sortType: '',
    show: false,
    roleShow: true,
    queryForm: { levelOneOrgId: '', levelTwoOrgId: '', levelThreeOrgId: '', levelFourOrgId: '', startDate: '', endDate: ''},
    query: { bankName: '', bankBranchName: '', bankSubBranchName: '', bankWorkstationName: '' },
    params: { parentId: ''},
    typeName: '',
    activityList: {},
    trainingActivityList: '',
    contentList: [{content: '1、人数：进入学习模块的人数'}, {content: '2、次数：进入学习模块的次数'}, {content: '3、平均时长：进入学习模块的平均时长'}, {content: '4、演练均分：参与演练人员的平均分'}, {content: '5、通关均分：参与通关人员的平均分'}],
    contentList1: [{content: '1、人数：进入学习模块的人数'}, {content: '2、次数：进入学习模块的次数'}, {content: '3、平均时长：进入学习模块的平均时长'}, {content: '4、演练均分：参与演练人员的平均分'}, {content: '5、通关均分：参与通关人员的平均分'}],
    contentList2: [{content: '1、人数：进入训练模块（包含我要训练和训练主页）的人数'}, {content: '2、次数：进入训练模块（包含我要训练和训练主页）的次数'}, {content: '3、平均时长：进入训练模块的平均时长'}, {content: '4、演练均分：参与演练人员的平均分'}, {content: '5、通关均分：参与通关人员的平均分'}],
    contentList3: [{content: '1、人数：进入e展业模块的人数'}, {content: '2、次数：进入e展业模块的次数'}, {content: '3、平均时长：进入e展业模块的平均时长'}],
    contentList4: [{content: '1、生成人数：生成计划书的人数'}, {content: '2、生成份数：生成计划书的次数'}],
    contentList5: [{content: '1、发起人数：发起VR会客的人数'}, {content: '2、发起次数：发起VR会客的次数'}, {content: '3、会客次数：进行VR会客的次数'}, {content: '4、平均时长：每次进行VR会客的平均时长'}],
    contentList6: [{content: '1、人数：进入培训活动详情的人数'}, {content: '2、次数：进入培训活动详情的次数'}, {content: '3、平均时长：参与培训活动的平均时长'}, {content: '4、演练均分：参与培训活动人员的演练平均分'}, {content: '5、通关均分：参与培训活动人员的通关平均分'}]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 安卓
    wx.setBackgroundColor({
      backgroundColor: '#0061E3',
    })
    // 兼容ios
    wx.setBackgroundColor({
      backgroundColorTop: '#0061E3',
      backgroundColorBottom: '#F3F6FA',
    })
    this.data.queryForm.startDate = (util.timestampToTime(Date.now() - 7 * 60 * 60 * 24 * 1000))
    this.data.queryForm.endDate = (util.timestampToTime(Date.now()))
    // this.data.queryForm.startDate = (util.timestampToTime(new Date().setDate(1)))
    // this.data.queryForm.endDate = (util.timestampToTime(new Date().setDate(1)))
    this.setData({
      queryForm: this.data.queryForm
    })
    this.getAllBankList()
    this.getbulletindata()
    // this.getTrainingActivitiesdata()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let code = ['admin-stewardCockpit']
    // this.setData({
    //   roleShow: (util.getArrEqual(code, app.globalData.roles)).length > 0 ? true : false
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  closeTip () {
    this.setData({
      hasTips: false
    })
  },
  showDetail (e) {
    let type = e.currentTarget.dataset.type
    switch(type) {
      case 'study':
         this.setData({ contentList: this.data.contentList1 })
         break;
      case 'training':
        this.setData({ contentList: this.data.contentList2 })
         break;
     case 'presentation':
      this.setData({ contentList: this.data.contentList3 })
         break;
      case 'plan':
        this.setData({ contentList: this.data.contentList4 })
        break;
      case 'vr':
        this.setData({ contentList: this.data.contentList5 })
        break;
      case 'trainingActive':
        this.setData({ contentList: this.data.contentList6 })
        break;
      default:
        this.setData({ contentList: this.data.contentList1 })
    }
    this.data.show = !this.data.show
    this.setData({
      show: this.data.show
    })
  },
  getcurrentOrgDetail () {
    app.api.get({
      url: 'cpic_org_getOrgLevel',
      data: { id: app.globalData.userInfo.orgId }
    }).then(res => {
      this.data.query.bankName = res.bank.id === app.globalData.userInfo.orgId ? '' : res.bank.orgName
      this.data.queryForm.levelOneOrgId = res.bank ? res.bank.id : ''
      this.data.bankindex = res.bank.id === app.globalData.userInfo.orgId ? 0 : ''

      this.data.query.bankBranchName = (res.branch && res.branch.id) === app.globalData.userInfo.orgId ? '' : (res.branch && res.branch.orgName)
      this.data.queryForm.levelTwoOrgId = res.branch ? res.branch.id : ''
      this.data.branchidindex = (res.branch && res.branch.id) === app.globalData.userInfo.orgId ? 0 : ''
      
      this.data.query.bankSubBranchName = (res.subBranch && res.subBranch.id) === app.globalData.userInfo.orgId ? '' : (res.subBranch && res.subBranch.orgName)
      this.data.queryForm.levelThreeOrgId = res.subBranch ? res.subBranch.id : ''
      this.data.subBranchindex = (res.subBranch && res.subBranch.id) === app.globalData.userInfo.orgId ? 0 : ''

      this.data.query.bankWorkstationName = res.site ? '' : ''
      this.data.queryForm.levelFourOrgId = res.site ? res.site.id : ''
      this.data.siteindex = res.site ? 0 : ''
      this.setData({
        query: this.data.query,
        queryForm: this.data.queryForm,
        bankindex: this.data.bankindex,
        branchidindex: this.data.branchidindex,
        subBranchindex: this.data.subBranchindex,
        siteindex: this.data.siteindex
      })
    })
  },
  bankChange: function(e) {
    // let toggleUrl
    // if (this.data.type === 'student') {
    //   toggleUrl = 'userAccessableBank_getAccessableBankOrgChildrenByParentId'
    // } else {
    //   toggleUrl = 'cpic_internal_org_getChildrenByParentId'
    // }
    this.data.queryForm.levelOneOrgId = this.data.bankidList[e.detail.value]
    this.data.params.parentId = this.data.bankidList[e.detail.value]
    this.setData({
      bankindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      if (res.length > 0) {
        this.data.branchList = []
        this.data.branchidList = []
        res.map(item => {
            this.data.branchList.push(item.orgName)
            this.data.branchidList.push(item.id)
          })
      } else {
        this.data.branchList = []
        this.data.subBranchList = []
        this.data.siteList = []
      }
      this.data.queryForm.levelTwoOrgId = ''
      this.data.queryForm.levelThreeOrgId = ''
      this.data.queryForm.levelFourOrgId = ''
      this.setData({
        branchList: this.data.branchList,
        subBranchList: this.data.subBranchList,
        siteList: this.data.siteList,
        branchidList: this.data.branchidList,
        branchidindex: '',
        subBranchindex: '',
        siteindex: '',
        queryForm: this.data.queryForm
      }, () => {
        console.log('赋值成功')
        this.getbulletindata()
        // this.getTrainingActivitiesdata()
      })
    })
  },
  branchChange: function(e) {
    // let toggleUrl
    // if (this.data.type === 'student') {
    //   toggleUrl = 'userAccessableBank_getAccessableBankOrgChildrenByParentId'
    // } else {
    //   toggleUrl = 'cpic_internal_org_getChildrenByParentId'
    // }
    this.data.queryForm.levelTwoOrgId = this.data.branchidList[e.detail.value]
    this.data.params.parentId = this.data.branchidList[e.detail.value]
    this.setData({
      branchidindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      if (res.length > 0) {
        this.data.subBranchList = []
        this.data.subBranchidList = []
        res.map(item => {
            this.data.subBranchList.push(item.orgName)
            this.data.subBranchidList.push(item.id)
          })
      } else {
        this.data.subBranchList = []
        this.data.siteList = []
      }
      this.data.queryForm.levelThreeOrgId = ''
      this.data.queryForm.levelFourOrgId = ''
      this.setData({
        queryForm: this.data.queryForm,
        subBranchindex: '',
        siteindex: '',
        subBranchList: this.data.subBranchList,
        siteList: this.data.siteList,
        subBranchidList: this.data.subBranchidList
      }, () => {
        this.getbulletindata()
        // this.getTrainingActivitiesdata()
      })
    })
  },
  subBranchChange: function(e) {
    // console.log(e, this.data.subBranchList)
    // let toggleUrl
    // if (this.data.type === 'student') {
    //   toggleUrl = 'userAccessableBank_getAccessableBankOrgChildrenByParentId'
    // } else {
    //   toggleUrl = 'cpic_internal_org_getChildrenByParentId'
    // }
    this.data.queryForm.levelThreeOrgId = this.data.subBranchidList[e.detail.value]
    this.data.params.parentId = this.data.subBranchidList[e.detail.value]
    this.setData({
      subBranchindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      if (res.length > 0) {
        this.data.siteList = []
        this.data.siteidList = []
        res.map(item => {
            this.data.siteList.push(item.orgName)
            this.data.siteidList.push(item.id)
          })
      } else {
        this.data.siteList = []
      }
      this.data.queryForm.levelFourOrgId = ''
      this.setData({
        queryForm: this.data.queryForm,
        siteindex: '',
        siteList: this.data.siteList,
        siteidList: this.data.siteidList
      }, () => {
        this.getbulletindata()
        // this.getTrainingActivitiesdata()
      })
    })
  },
  siteChange: function(e) {
    this.data.queryForm.levelFourOrgId = this.data.siteidList[e.detail.value]
    this.setData({
      siteindex: e.detail.value,
      queryForm: this.data.queryForm
    })
    this.getbulletindata()
    // this.getTrainingActivitiesdata()
  },
  // 开始时间
  bindstartDateChange: function(e) {
    const oneDay = 60 * 60 * 24 * 1000
    const startDate = e.detail.value
    const endDate = this.data.queryForm.endDate
    let arrEnd = []
    if(endDate){
      arrEnd = endDate.split('-')
    }
    const arrStart = startDate.split('-')
    const sy = arrStart[0]
    const sm = arrStart[1]
    const sd = arrStart[2]
    const y = arrEnd[0]
    const m = arrEnd[1]
    const d = arrEnd[2]
    if((new Date(y,m,d).getTime() - new Date(sy,sm,sd).getTime()) / oneDay >60){
      wx.showModal({
        content: '时间范围不能超过60天',
        showCancel:false
      })
      return false
    }
    this.setData({
      startdate: e.detail.value
    })
    this.data.queryForm.startDate = e.detail.value
    this.setData({
      queryForm: this.data.queryForm
    })
    this.getbulletindata()
    // this.getTrainingActivitiesdata()
  },
  // 结束时间
  bindendDateChange: function(e) {
    console.log(e.detail.value,'e.detail.value=');
    const oneDay = 60 * 60 * 24 * 1000
    const endDate = e.detail.value
    const startDate = this.data.queryForm.startDate
    let arrStart = []
    if(startDate){
      arrStart = startDate.split('-')
    }
    const sy = arrStart[0]
    const sm = arrStart[1]
    const sd = arrStart[2]
    const arrEnd = endDate.split('-')
    const y = arrEnd[0]
    const m = arrEnd[1]
    const d = arrEnd[2]
    if((new Date(y,m,d).getTime() - new Date(sy,sm,sd).getTime()) / oneDay >60){
      wx.showModal({
        content: '时间范围不能超过60天',
        showCancel:false
      })
      return false
    }
    this.setData({
      enddate: e.detail.value
    })
    this.data.queryForm.endDate = e.detail.value
    this.setData({
      queryForm: this.data.queryForm
    })
    this.getbulletindata()
    // this.getTrainingActivitiesdata()
  },
  toActiveDetail (e) {    
    let paramsIndex = {
      bankindex: this.data.bankindex,
      branchidindex: this.data.branchidindex,
      subBranchindex: this.data.subBranchindex,
      siteindex: this.data.siteindex
    } 
    let queryForm = JSON.stringify(this.data.queryForm)
    let queryIndex = JSON.stringify(paramsIndex)
    wx.navigateTo({
      url: `/myself/pages/table-list/tableList?queryForm=${queryForm}&queryIndex=${queryIndex}`
    })
  },

  toDetail (e) {
    // if (!this.data.queryForm.levelFourOrgId) return
    let type = e.currentTarget.dataset.type
    let paramsIndex = {
      bankindex: this.data.bankindex,
      branchidindex: this.data.branchidindex,
      subBranchindex: this.data.subBranchindex,
      siteindex: this.data.siteindex
    } 
    let queryForm = JSON.stringify(this.data.queryForm)
    let queryIndex = JSON.stringify(paramsIndex)
    console.log(type, paramsIndex, queryForm)
    switch(type) {
      case 'study':
         this.setData({ fields: this.data.fields1, typeName: '学习' })
         break;
      case 'training':
        this.setData({ fields: this.data.fields2, typeName: '训练' })
         break;
     case 'presentation':
      this.setData({ fields: this.data.fields3, typeName: 'e展业' })
         break;
      case 'plan':
        this.setData({ fields: this.data.fields4, typeName: '计划书' })
        break;
      case 'vr':
        this.setData({ fields: this.data.fields5, typeName: 'VR会客厅' })
        break;
      case 'trainingActive':
          this.setData({ fields: this.data.fields6, typeName: '考试' })
          break;
      default:
        this.setData({ fields: this.data.fields1, typeName: '学习' })
    }
    let fields = JSON.stringify(this.data.fields)
    wx.navigateTo({
      url: `/echarts/pages/myself/activity-detail/activityDetail?queryForm=${queryForm}&fields=${fields}&type=${type}&typeName=${this.data.typeName}&queryIndex=${queryIndex}`
    })
  },
  // 客户经理下的组织
  getAdminOrgList () {
  app.api.get({
    url: 'cpic_internal_org_getTreeByParentId',
    data: { orgId: this.data.orgId }
  }).then(res => {
    // 银行
    let bankList = []
    let bankidList = []
    console.log(res)
    if (res.length > 0) {
      res.map(item => {
        bankList.push(item.orgName)
        bankidList.push(item.id)
      })
    }
    this.setData({
      bankList: bankList,
      bankidList: bankidList,
    })
  })
},
// 获取所有银行
getAllBankList () {
  app.api.post({
    url: 'userAccessableBank_getAccessableBank',
    data: {}
  }).then(res => {
    // 银行
    let bankList = []
    let bankidList = []
    if (res.length > 0) {
      res.map(item => {
        bankList.push(item.orgName)
        bankidList.push(item.id)
      })
    }
    this.setData({
      bankList: bankList,
      bankidList: bankidList,
    })
  })
},
  // 活动量看板数据除了培训活动的
  getbulletindata () {
    let params = JSON.parse(JSON.stringify(this.data.queryForm))
    console.log(params)
    app.api.post({
      url: 'report_activity_activityKanban',
      data: params
    }).then(res => {
      this.setData({
        activityList: res || {}
      })
      console.log(this.data.activityList)
    })
    app.api.post({
      url: 'qryStudyToTalNum',
      data: params
    }).then(res => {
      this.setData({
        studyInfo: res || {}
      })
    })
    app.api.post({
      url: 'qryTrainingToTalNum',
      data: params
    }).then(res => {
      this.setData({
        trainInfo: res || {}
      })
    })
    app.api.post({
      url: 'report_coaching_queryActBoard',
      data: params
    }).then(res => {
      this.setData({
        examInfo: res || {}
      })
    })
  },
  // 活动量看板数据培训活动的
  // getTrainingActivitiesdata () {
  //   let params = JSON.parse(JSON.stringify(this.data.queryForm))
  //   console.log(params)
  //   app.api.post({
  //     url: 'report_activity_activityCoaching',
  //     data: params
  //   }).then(res => {
  //     this.setData({
  //       trainingActivityList: res
  //     })
  //     console.log(this.data.trainingActivityList)
  //   })
  // }
})